#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

#include "eventDriven.h"

#define BUTTON_CLICK 1
#define DOCUMENT_READY 2
#define HIGH_FUNCTION 3
#define FUNC_PASS 4
struct test {
    int a;
    int b;
};
void onFuncPass(void *param) {
    Event *event = param;
    int size = event->size;
    void (*p)(int);
    p = event->param;
    p(size);
    printf("onFuncPass\n");
}
void testfun(int a) {
    printf("test %d\n", a);
}
void onHighFunction(void *param) {
    char timeStr[100];
    Event *event = param;
    struct test *t = (struct test*)event->param;
    int size = event->size;
    time_t now = time(NULL);
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&now));
    printf("处理时: %s,", timeStr);
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&event->eventSTime));
    printf("事件发生时间: %s,", timeStr);
    printf("按钮点击事件触发，参数是a是：%d，b是%d，sizeof(test)%ld，size%d\n", t->a, t->b, sizeof(struct test), size);
    free(t);
}
void onButtonClick(void *param) {
    char timeStr[100];
    Event *event = param;
    int size = event->size;
    time_t now = time(NULL);
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&now));
    printf("处理时: %s,", timeStr);
    strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&event->eventSTime));
    printf("事件发生时间: %s,", timeStr);
    printf("按钮点击事件触发，参数是 %d\n", size);
}
void onDocumentReady(void *param) {
    Event *event = param;
    int size = event->size;
    printf("文档就绪事件触发，参数是 %d\n", size);
}

EventHandler events[]={
    {BUTTON_CLICK,onButtonClick},
    {DOCUMENT_READY,onDocumentReady},
    {HIGH_FUNCTION,onHighFunction},
    {FUNC_PASS,onFuncPass}
}; // 事件队列

int main() {
    EventEmitter eventEmitter;
    pthread_t thread;
    struct test *t = (struct test*)malloc(sizeof(struct test));
    t->a = 1;
    t->b = 2;
    initEventEmitter(&eventEmitter, events, 50, sizeof(events)/sizeof(EventHandler));
    pthread_create(&thread, NULL, handleEvent, &eventEmitter);
    pushEvent(&eventEmitter, (Event){time(NULL), BUTTON_CLICK, NULL, 1});
    // handleEventOnce(&eventEmitter);
    // sleep(1);
    for(int i = 0; i < 20; i++){
        int ret = pushEvent(&eventEmitter, (Event){time(NULL), BUTTON_CLICK, NULL, i});
        printf("event %d ret:%d\n", i, ret);
        // sleep(1);
    }
    pushEvent(&eventEmitter, (Event){time(NULL), FUNC_PASS, testfun, sizeof(testfun)});
    pushEvent(&eventEmitter, (Event){time(NULL), DOCUMENT_READY, NULL, 2});
    pushEvent(&eventEmitter, (Event){time(NULL), HIGH_FUNCTION, t, sizeof(struct test)});
    sleep(2);
    // handleEventOnce(&eventEmitter);
    return 0;
}
